<?php

namespace app\admin\controller;

use app\admin\lib\exception\BaseException;
use app\admin\service\UserService;
use app\admin\service\AvatarService;
use app\admin\validate\Common as CommonValidate;
use app\BaseController;

class User extends BaseController
{
    protected $userService;
    protected $avatarService;

    protected function initialize()
    {
        parent::initialize();
        $this->userService = new UserService();
        $this->avatarService = new AvatarService();
    }

    /**
     * 获取用户列表
     */
    public function list()
    {
        try {
            $data = $this->request->only(['limit', 'page'], 'get');

            validate(CommonValidate::class)
                ->scene('list')
                ->check($data);

            $result = $this->userService->getUserList((int)$data['page'], (int)$data['limit']);

            return json([
                'code' => 200,
                'message' => '查询成功',
                'data' => $result
            ]);
        } catch (\Exception $e) {
            throw new BaseException([
                'code' => 400,
                'message' => $e->getMessage(),
                'errorCode' => 10001,
            ]);
        }
    }

    /**
    * 用户注册
    */
    public function register()
    {
        $avatarFile = $this->request->file('avatar');
        $data = $this->request->only([
            'username', 'password', 'password_confirm', 'email', 'phone'
        ], 'post');

        try {
            // 处理头像上传
            if ($avatarFile) {
                // 先创建临时用户ID，用于文件命名
                $tempUserId = time() . rand(1000, 9999);
                $data['avatar'] = $this->avatarService->uploadAvatar($avatarFile, $tempUserId);
            }

            validate(CommonValidate::class)->scene('register')->check($data);

            $result = $this->userService->register($data);

            return json([
                'code' => 200,
                'message' => '注册成功',
                'data' => $result['user_data'],
                'token' => $result['token'],
                'expire' => $result['expire']
            ]);
        } catch (\Exception $e) {
            throw new BaseException([
                'code' => 400,
                'message' => $e->getMessage(),
                'errorCode' => 60001
            ]);
        }
    }
}
